<template>
  <basic-container>
    <avue-crud :option="option"
               v-model:search="search"
               v-model:page="page"
               v-model="form"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.product_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-tooltip
          class="item"
          effect="dark"
          content="将JSON格式的物模型配置文件读取，并导入覆盖至对应产品的物模型草稿数据"
          placement="top"
        >
          <el-button v-if="userInfo.authority.includes('admin')"
                     icon="el-icon-upload"
                     plain
                     @click="handleImport">物模型 导入
          </el-button>
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          content="将JSON格式的物模型配置读取，并导出带有产品信息的物模型配置文件集合"
          placement="top"
        >
          <el-button v-if="userInfo.authority.includes('admin')"
                     icon="el-icon-download"
                     plain
                     @click="handleExport">物模型 导出
          </el-button>
        </el-tooltip>
      </template>
      <template #menu="{row,index,size}">
        <el-button text type="primary"
                   icon="el-icon-setting"
                   @click="viewDetail(row)">配置
        </el-button>
        <el-button text
                   type="primary"
                   icon="el-icon-edit"
                   @click="$refs.crud.rowEdit(row,index)">编辑
        </el-button>
        <el-button text type="primary"
                   icon="el-icon-iphone"
                   @click="viewDevice(row)">管理设备
        </el-button>
        <el-button text
                   type="primary"
                   icon="el-icon-delete"
                   @click="$refs.crud.rowDel(row,index)">删除
        </el-button>
      </template>
      <template #productName="{ row }">
        <el-tag size="large" style="cursor:pointer" @click="viewDetail(row)">{{ row.productName }}</el-tag>
      </template>
      <template #productKey-form="{ }">
        <el-input v-model="form.productKey" placeholder="请输入 产品编码">
          <template #append>
            <el-button @click="generateProductKey">自动生成</el-button>
          </template>
        </el-input>
      </template>
      <template #productSecret-form="{ }">
        <el-input v-model="form.productSecret" placeholder="请输入 产品密钥">
          <template #append>
            <el-button @click="generateProductSecret">自动生成</el-button>
          </template>
        </el-input>
      </template>
      <template #status="{ row }">
        <el-switch
            v-model="row.status"
            inline-prompt
            @change="slotChange(row)"
            active-text="已上线"
            inactive-text="开发中"
            :active-value="1"
            :inactive-value="0"
        />
      </template>
      <template #imgBox="{row}">
        <img style="width: 150px;height: 150px" :src="row.logo||defaultLogo" alt="">
      </template>
    </avue-crud>
    <el-dialog v-model="visibleImport" :before-close="beforeCloseImport" title="物模型导入" width="600">
      <el-upload
        drag
        action="/api/blade-iot/product/version/tsl-import-batch"
        accept=".json"
        :show-file-list="false"
        :headers="uploadHeaders"
        :on-success="uploadSuccess"
        :on-error="uploadError"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖动文件上传 <em>或者点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传JSON格式的物模型文件
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove} from "@/api/iot/product";
import {option} from "@/option/iot/product";
import {mapGetters} from "vuex";
import func from '@/utils/func';
import { exportBlob } from '@/api/common';
import { downloadJson } from '@/utils/util';
import { getToken } from '@/utils/auth';

export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      visibleImport: false,
      page: {
        pageSize: 12,
        pageSizes: [12, 24, 48, 72, 96, 120],
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option(this),
      data: [],
      uploadHeaders: {
        'Blade-Auth': `bearer ${getToken()}`,
        'Blade-Requested-With': 'BladeHttpRequest'
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.product_add, false),
        viewBtn: this.validData(this.permission.product_view, false),
        delBtn: this.validData(this.permission.product_delete, false),
        editBtn: this.validData(this.permission.product_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    defaultLogo() {
      const basePath = import.meta.env.VITE_APP_BASE;
      const logoPath = `/svg/icon2.svg`;
      return basePath === "/" ? logoPath : `${basePath}${logoPath}`;
    },
  },
  methods: {
    generateProductKey() {
      this.form.productKey = func.strGenerate(12);
    },
    generateProductSecret() {
      this.form.productSecret = func.strGenerate(16);
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
    },
    handleImport() {
      this.$confirm('覆盖各产品物模型的草稿数据后无法找回，是否继续？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.visibleImport = true;
        })
    },
    beforeCloseImport() {
      this.visibleImport = false;
    },
    uploadSuccess(response) {
      console.log(response);
      this.beforeCloseImport();
      this.$message.success("物模型数据导入完毕！");
    },
    uploadError(error) {
      console.log(error.message);
      this.$message.error("导入失败请检查文件格式！");
    },
    handleExport() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定导出所选品类的物模型集合？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          exportBlob(
            `/blade-iot/product/version/tsl-export-batch?productIds=${this.ids}`
          ).then(res => {
            downloadJson(res.data, `product_tsl_batch.json`);
          });
        })
    },
    slotChange(row) {
      if (!row.id) {
        return;
      }
      update(row).then(
          () => {
            this.onLoad(this.page);
          },
          error => {
            window.console.log(error);
          }
      );
    },
    viewDetail(row) {
      this.$router.push({
        path: `/iot/product/detail/${row.productKey}/${row.id}`,
      });
    },
    viewDevice(row) {
      this.$router.push({
        path: `/iot/product/detail/${row.productKey}/${row.id}`,
        query:{
          activeKey: 'subset',
        }
      });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const {
        productName,
        productKey,
        deviceType,
        status,
      } = this.query;

      let values = {
        productName_like: productName,
        productKey_like: productKey,
        deviceType_equal: deviceType,
        status_equal: status,
      };

      getList(page.currentPage, page.pageSize, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
.imgBox {
  .avue-crud__grid__value{
    position: absolute;
    width: 150px;
    height: 150px;
    right: 20px;
    bottom: 60px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .avue-crud__grid__label {
    &:after{
      display: none;
    }
  }
}
</style>
